from fastapi import Depends, Body
from fastapi.security import OAuth2PasswordRequestForm
from pydantic import BaseModel
from sqlalchemy.orm import Session
from datetime import datetime, timedelta
from jose import jwt

from schemas import crud
from config import ACCESS_TOKEN_EXPIRE_MINUTES, SECRET_KEY, ALGORITHM
from middlewares.middlewares import generate_response
from routes.routers import v1
from schemas.database import get_db


@v1.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    用户 = crud.authenticate_user(db, form_data.username, form_data.password)
    if not 用户:
        return generate_response(None, 401, "用户名或密码错误")

    访问令牌 = create_access_token(data={"sub": 用户.username})
    return generate_response({"access_token": 访问令牌, "token_type": "bearer"})

class Userlogin(BaseModel):
    username: str
    password: str

@v1.post("/auth/signin")
async def login(jsonData: Userlogin, db: Session = Depends(get_db)):
    用户 = crud.authenticate_user(db, jsonData.username, jsonData.password)
    if not 用户:
        return generate_response(None, 401, "用户名或密码错误")

    访问令牌 = create_access_token(data={"sub": 用户.username})
    return generate_response({"access_token": 访问令牌, "token_type": "bearer"})

def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt